package com.xky.ui.module.salesManagement.add;

import com.xky.pojo.SalesShipments;
import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加销售发货单类
 */
public class AddSalesShipment extends JDialog {

    // 表单字段
    private JTextField shipmentNumberField; // shipmentNumber - 发货单号
    private JTextField orderIdField;        // orderId - 关联订单ID
    private JTextField warehouseIdField;    // warehouseId - 发货仓库ID
    private JTextField shipmentDateField;   // shipmentDate - 发货日期
    private JTextField carrierField;        // carrier - 承运商
    private JTextField trackingNumberField; // trackingNumber - 物流单号
    private JComboBox<String> shippingMethodComboBox; // shippingMethod - 运输方式
    private JComboBox<String> statusComboBox; // status - 状态
    private JTextArea notesArea;            // notes - 备注

    // 日期格式
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    
    // 状态映射
    private static final Map<String, String> STATUS_MAP = new HashMap<>();
    static {
        STATUS_MAP.put("待发货", "pending");
        STATUS_MAP.put("已发货", "shipped");
        STATUS_MAP.put("运输中", "in_transit");
        STATUS_MAP.put("已签收", "delivered");
        STATUS_MAP.put("已取消", "cancelled");
    }
    // 颜色常量
    private static final Color PRIMARY_COLOR = new Color(52, 152, 219); // 蓝色
    private static final Color SECONDARY_COLOR = new Color(41, 128, 185); // 深蓝色
    private static final Color BACKGROUND_COLOR = new Color(248, 249, 250); // 浅灰色背景
    private static final Color TEXT_COLOR = new Color(44, 62, 80); // 深色文本
    private static final Color FIELD_BACKGROUND = new Color(255, 255, 255); // 输入框背景
    private static final Color SUCCESS_COLOR = new Color(46, 204, 113); // 成功绿色
    private static final Color CANCEL_COLOR = new Color(189, 195, 199); // 取消按钮灰色

    /**
     * 构造方法
     */
    public AddSalesShipment() {
        try {
            // 使用系统外观
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 设置窗口属性
        setTitle("添加销售发货单");
        setSize(500, 700);
        setLocationRelativeTo(null);
        setModal(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        
        // 初始化组件
        initComponents();
        
        // 显示对话框
        setVisible(true);
    }
    
    /**
     * 初始化所有组件
     */
    private void initComponents() {
        // 创建主面板
        JPanel mainPanel = new JPanel(new BorderLayout(0, 0));
        mainPanel.setBackground(BACKGROUND_COLOR);
        
        // 创建顶部标题面板
        JPanel headerPanel = createHeaderPanel();
        
        // 创建表单面板
        JScrollPane formPanel = createFormPanel();
        
        // 创建按钮面板
        JPanel buttonPanel = createButtonPanel();
        
        // 将面板添加到主面板
        mainPanel.add(headerPanel, BorderLayout.NORTH);
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加到对话框
        add(mainPanel);
    }
    
    /**
     * 创建标题面板
     */
    private JPanel createHeaderPanel() {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                int w = getWidth();
                int h = getHeight();
                GradientPaint gp = new GradientPaint(0, 0, PRIMARY_COLOR, 0, h, SECONDARY_COLOR);
                g2d.setPaint(gp);
                g2d.fillRect(0, 0, w, h);
            }
        };
        panel.setLayout(new BorderLayout());
        panel.setPreferredSize(new Dimension(500, 60));
        
        JLabel titleLabel = new JLabel("新增销售发货单", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setBorder(new EmptyBorder(10, 0, 10, 0));
        
        panel.add(titleLabel, BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 创建表单面板
     */
    private JScrollPane createFormPanel() {
        // 初始化输入组件
        shipmentNumberField = createTextField(15); // shipmentNumber - 发货单号
        orderIdField = createTextField(15);        // orderId - 关联订单ID
        warehouseIdField = createTextField(15);    // warehouseId - 发货仓库ID
        shipmentDateField = createTextField(15);   // shipmentDate - 发货日期
        shipmentDateField.setText(LocalDate.now().format(DATE_FORMATTER));
        shipmentDateField.setToolTipText("格式：yyyy-MM-dd");
        
        carrierField = createTextField(15);        // carrier - 承运商
        trackingNumberField = createTextField(15); // trackingNumber - 物流单号
        
        String[] shippingMethods = {"顺丰速运", "京东物流", "中通快递","圆通速递","申通快递","极兔速递"};
        shippingMethodComboBox = createComboBox(shippingMethods); // shippingMethod - 运输方式
        
        String[] statuses = {"待发货", "已发货", "运输中", "已签收", "已取消"};
        statusComboBox = createComboBox(statuses); // status - 状态
        
        notesArea = createTextArea(5, 20); // notes - 备注
        
        // 创建主表单面板
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
        formPanel.setBackground(BACKGROUND_COLOR);
        formPanel.setBorder(new EmptyBorder(15, 20, 15, 20));
        
        // 基本信息面板
        JPanel basicInfoPanel = createSectionPanel("基本信息");
        GridBagLayout basicLayout = new GridBagLayout();
        basicInfoPanel.setLayout(basicLayout);
        
        // 添加基本信息字段
        addFormField(basicInfoPanel, "发货单号:", shipmentNumberField, 0); // shipmentNumber
        addFormField(basicInfoPanel, "关联订单ID:", orderIdField, 1);      // orderId
        addFormField(basicInfoPanel, "发货仓库ID:", warehouseIdField, 2);  // warehouseId
        
        // 发货信息面板
        JPanel shipmentInfoPanel = createSectionPanel("发货信息");
        GridBagLayout shipmentLayout = new GridBagLayout();
        shipmentInfoPanel.setLayout(shipmentLayout);
        
        // 添加发货信息字段
        addFormField(shipmentInfoPanel, "发货日期:", shipmentDateField, 0); // shipmentDate
        addFormField(shipmentInfoPanel, "承运商:", carrierField, 1);     // carrier
        addFormField(shipmentInfoPanel, "物流单号:", trackingNumberField, 2); // trackingNumber
        addFormField(shipmentInfoPanel, "运输方式:", shippingMethodComboBox, 3); // shippingMethod
        addFormField(shipmentInfoPanel, "状态:", statusComboBox, 4);       // status
        
        // 备注信息面板
        JPanel notesPanel = createSectionPanel("备注信息");
        notesPanel.setLayout(new BorderLayout(0, 5));
        
        JScrollPane notesScrollPane = new JScrollPane(notesArea);
        notesScrollPane.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
        notesScrollPane.setPreferredSize(new Dimension(0, 80));
        
        notesPanel.add(notesScrollPane, BorderLayout.CENTER);
        
        // 添加所有部分到表单面板
        formPanel.add(basicInfoPanel);
        formPanel.add(Box.createVerticalStrut(10));
        formPanel.add(shipmentInfoPanel);
        formPanel.add(Box.createVerticalStrut(10));
        formPanel.add(notesPanel);
        
        JScrollPane scrollPane = new JScrollPane(formPanel);
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        
        return scrollPane;
    }
    
    /**
     * 创建分节面板
     */
    private JPanel createSectionPanel(String title) {
        JPanel panel = new JPanel();
        panel.setBackground(BACKGROUND_COLOR);
        panel.setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(PRIMARY_COLOR, 1, true),
            title,
            TitledBorder.LEFT,
            TitledBorder.TOP,
            new Font("微软雅黑", Font.BOLD, 12)
        ));
        return panel;
    }
    
    /**
     * 添加表单字段到面板
     */
    private void addFormField(JPanel panel, String labelText, JComponent field, int row) {
        GridBagConstraints labelConstraints = new GridBagConstraints();
        labelConstraints.gridx = 0;
        labelConstraints.gridy = row;
        labelConstraints.anchor = GridBagConstraints.EAST;
        labelConstraints.insets = new Insets(5, 5, 5, 10);
        
        GridBagConstraints fieldConstraints = new GridBagConstraints();
        fieldConstraints.gridx = 1;
        fieldConstraints.gridy = row;
        fieldConstraints.fill = GridBagConstraints.HORIZONTAL;
        fieldConstraints.weightx = 1.0;
        fieldConstraints.insets = new Insets(5, 0, 5, 5);
        
        JLabel label = new JLabel(labelText);
        label.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        label.setForeground(TEXT_COLOR);
        
        panel.add(label, labelConstraints);
        panel.add(field, fieldConstraints);
    }
    
    /**
     * 创建按钮面板
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 15));
        panel.setBackground(BACKGROUND_COLOR);
        
        JButton saveButton = new JButton("保存");
        styleButton(saveButton, SUCCESS_COLOR);
        
        JButton cancelButton = new JButton("取消");
        styleButton(cancelButton, CANCEL_COLOR);
        
        panel.add(saveButton);
        panel.add(cancelButton);
        
        // 添加事件监听
        saveButton.addActionListener(e -> saveShipment());
        cancelButton.addActionListener(e -> dispose());
        
        return panel;
    }
    
    /**
     * 设置按钮样式
     */
    private void styleButton(JButton button, Color color) {
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setForeground(Color.WHITE);
        button.setBackground(color);
        button.setFocusPainted(false);
        button.setBorderPainted(false);
        button.setPreferredSize(new Dimension(100, 36));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
    
    /**
     * 创建统一样式的文本框
     */
    private JTextField createTextField(int columns) {
        JTextField field = new JTextField(columns);
        field.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        field.setPreferredSize(new Dimension(field.getPreferredSize().width, 25));
        field.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(220, 220, 220)),
            BorderFactory.createEmptyBorder(2, 5, 2, 5)
        ));
        field.setBackground(FIELD_BACKGROUND);
        return field;
    }
    
    /**
     * 创建统一样式的下拉框
     */
    private JComboBox<String> createComboBox(String[] items) {
        JComboBox<String> comboBox = new JComboBox<>(items);
        comboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        comboBox.setPreferredSize(new Dimension(comboBox.getPreferredSize().width, 25));
        comboBox.setBackground(FIELD_BACKGROUND);
        return comboBox;
    }

    /**
     * 创建统一样式的文本区域
     */
    private JTextArea createTextArea(int rows, int columns) {
        JTextArea area = new JTextArea(rows, columns);
        area.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        area.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        area.setBackground(FIELD_BACKGROUND);
        return area;
    }

    /**
     * 保存发货单
     */
    private void saveShipment() {
        try {
            // 验证输入
            if (!validateInput()) {
                return;
            }
            
            // 构造发货单对象
            SalesShipments shipment = constructSalesShipment();
            
            // 检查订单ID是否存在
            if (!orderExists(shipment.getOrderId())) {
                JOptionPane.showMessageDialog(this, 
                    "无法保存发货单：订单ID " + shipment.getOrderId() + " 不存在，请输入正确的订单ID", 
                    "错误", JOptionPane.ERROR_MESSAGE);
                orderIdField.requestFocus();
                return;
            }
            
            // 插入数据库
            if (insertSalesShipment(shipment)) {
                JOptionPane.showMessageDialog(this, 
                    "发货单保存成功", 
                    "保存成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, 
                    "发货单保存失败，请重试", 
                    "保存失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, 
                "保存过程中出错: " + e.getMessage(), 
                "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 验证输入数据
     * @return 是否验证通过
     */
    private boolean validateInput() {
        // 验证发货单号
        if (shipmentNumberField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, 
                "请输入发货单号", 
                "输入错误", JOptionPane.ERROR_MESSAGE);
            shipmentNumberField.requestFocus();
            return false;
        }
        
        // 验证订单ID
        String orderIdText = orderIdField.getText().trim();
        if (orderIdText.isEmpty()) {
            JOptionPane.showMessageDialog(this, 
                "请输入订单ID", 
                "输入错误", JOptionPane.ERROR_MESSAGE);
            orderIdField.requestFocus();
            return false;
        }
        try {
            Integer.parseInt(orderIdText);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, 
                "订单ID必须是数字", 
                "输入错误", JOptionPane.ERROR_MESSAGE);
            orderIdField.requestFocus();
            return false;
        }
        
        // 验证仓库ID
        String warehouseIdText = warehouseIdField.getText().trim();
        if (warehouseIdText.isEmpty()) {
            JOptionPane.showMessageDialog(this, 
                "请输入仓库ID", 
                "输入错误", JOptionPane.ERROR_MESSAGE);
            warehouseIdField.requestFocus();
            return false;
        }
        try {
            Integer.parseInt(warehouseIdText);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, 
                "仓库ID必须是数字", 
                "输入错误", JOptionPane.ERROR_MESSAGE);
            warehouseIdField.requestFocus();
            return false;
        }
        
        // 验证日期格式
        String shipmentDateText = shipmentDateField.getText().trim();
        if (!shipmentDateText.isEmpty()) {
            try {
                LocalDate.parse(shipmentDateText, DATE_FORMATTER);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, 
                    "发货日期格式不正确，请使用yyyy-MM-dd格式", 
                    "输入错误", JOptionPane.ERROR_MESSAGE);
                shipmentDateField.requestFocus();
                return false;
            }
        }
        
        return true;
    }

    /**
     * 构造发货单对象
     * @return 发货单对象
     */
    private SalesShipments constructSalesShipment() {
        SalesShipments shipment = new SalesShipments();
        
        // shipmentId 由数据库自动生成
        shipment.setShipmentNumber(shipmentNumberField.getText().trim()); // shipmentNumber - 发货单号
        shipment.setOrderId(Integer.parseInt(orderIdField.getText().trim())); // orderId - 关联订单ID
        shipment.setWarehouseId(Integer.parseInt(warehouseIdField.getText().trim())); // warehouseId - 发货仓库ID
        
        // 设置日期
        if (!shipmentDateField.getText().trim().isEmpty()) {
            LocalDate shipmentDate = LocalDate.parse(shipmentDateField.getText().trim(), DATE_FORMATTER);
            shipment.setShipmentDate(shipmentDate); // shipmentDate - 发货日期
        }
        
        shipment.setCarrier(carrierField.getText().trim()); // carrier - 承运商
        shipment.setTrackingNumber(trackingNumberField.getText().trim()); // trackingNumber - 物流单号
        shipment.setShippingMethod((String) shippingMethodComboBox.getSelectedItem()); // shippingMethod - 运输方式
        
        // 根据选择的状态设置状态代码
        String statusText = (String) statusComboBox.getSelectedItem();
        String statusCode = STATUS_MAP.get(statusText);
        shipment.setStatus(statusCode); // status - 状态
        
        shipment.setNotes(notesArea.getText().trim()); // notes - 备注
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        shipment.setCreatedTime(now); // createdTime - 创建时间
        shipment.setUpdatedTime(now); // updatedTime - 更新时间
        
        return shipment;
    }

    /**
     * 检查订单ID是否存在
     * @param orderId 订单ID
     * @return 订单ID是否存在
     */
    private boolean orderExists(int orderId) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        
        try {
            connection = DBUtils.getConnection();
            String sql = "SELECT COUNT(*) FROM sales_orders WHERE order_id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, orderId);
            resultSet = preparedStatement.executeQuery();
            
            if (resultSet.next()) {
                return resultSet.getInt(1) > 0;
            }
            
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    /**
     * 插入发货单到数据库
     * @param shipment 发货单对象
     * @return 是否插入成功
     */
    private boolean insertSalesShipment(SalesShipments shipment) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        try {
            conn = DBUtils.getConnection();
            
            String sql = "INSERT INTO sales_shipments (shipment_number, order_id, warehouse_id, shipment_date, carrier, tracking_number, shipping_method, status, notes, created_time, updated_time) " +
                         "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            pstmt = conn.prepareStatement(sql);
            int index = 1;
            pstmt.setString(index++, shipment.getShipmentNumber());
            pstmt.setInt(index++, shipment.getOrderId());
            pstmt.setInt(index++, shipment.getWarehouseId());
            
            if (shipment.getShipmentDate() != null) {
                pstmt.setDate(index++, java.sql.Date.valueOf(shipment.getShipmentDate()));
            } else {
                pstmt.setNull(index++, java.sql.Types.DATE);
            }
            
            pstmt.setString(index++, shipment.getCarrier());
            pstmt.setString(index++, shipment.getTrackingNumber());
            pstmt.setString(index++, shipment.getShippingMethod());
            pstmt.setString(index++, shipment.getStatus());
            pstmt.setString(index++, shipment.getNotes());
            pstmt.setTimestamp(index++, Timestamp.valueOf(shipment.getCreatedTime()));
            pstmt.setTimestamp(index++, Timestamp.valueOf(shipment.getUpdatedTime()));
            
            int rows = pstmt.executeUpdate();
            return rows > 0;
            
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(conn, pstmt, null);
        }
    }

    public static void main(String[] args) {
        new AddSalesShipment();
    }
} 